//
//  ZGLShowCollectionVC.m
//  Faker
//
//  Created by dllo on 15/11/7.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "ZGLShowCollectionVC.h"
#import "ZGLPicVCModel.h"
#import "RFQuiltLayout.h"
#import "ZGLWaterCell.h"
#import "ZGLPhotoModel.h"
#include "ZGLPhotoCell.h"
#import "ZGLShowCollectionVC.h"
#import "ZGLNaviView.h"
#import <UIImageView+AFNetworking.h>

@interface ZGLShowCollectionVC () <RFQuiltLayoutDelegate, UICollectionViewDataSource, UICollectionViewDelegate ,UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UICollectionView *showCollectionView;
@property (nonatomic, strong) NSMutableArray *modelArr;
@property (nonatomic, strong) ZGLNaviView *titleView;
@property (nonatomic, assign) NSInteger currentPage;


@end

@implementation ZGLShowCollectionVC

- (void)dealloc {
    _showCollectionView.delegate = nil;
    _showCollectionView.dataSource = nil;
    [_titleView.backButton removeTarget:self action:@selector(backButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [_titleView.downButton removeTarget:self action:@selector(downButton:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setNavigationBar {
    _titleView = [[ZGLNaviView alloc] initWithFrame:CGRectMake(0, 0, ScaleX * 375, 64)];
    [_titleView.downButton setImage:[UIImage imageNamed:@"xiazai"] forState:(UIControlStateNormal)];
    [_titleView.backButton addTarget:self action:@selector(backButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [_titleView.downButton addTarget:self action:@selector(downButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:_titleView];
}
- (void)backButton:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)downButton:(UIButton *)button {
    UIImageView *gtp = [[UIImageView alloc] init];
    ZGLPhotoModel *model = _modelArr[_currentPage];
    [gtp setImageWithURL:[NSURL URLWithString:model.raw_url]];
    UIImageWriteToSavedPhotosAlbum(gtp.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        }];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:^{
        }];

    }else{
        msg = @"保存图片成功!请到相册里查看" ;
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        /* 照片是否可以编辑 */
        picker.allowsEditing = YES;
        picker.delegate = self;
        /* 根据照片来源确定AlertAction */
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleActionSheet];
        /* 判断相册是否可以访问 */
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"立即前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self presentViewController:picker animated:NO completion:^{}];
            }];
            
            [alert addAction:action1];
        }
        
        
        
        UIAlertAction *cancel  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
            
        }];
        [alert addAction:cancel];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        

    }
}




- (void)setPhotoModel:(ZGLPicVCModel *)photoModel {
    if (_photoModel != photoModel) {
        _photoModel = photoModel;
    }
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    for (NSDictionary *dic in photoModel.media) {
        ZGLPhotoModel *model = [ZGLPhotoModel modWithDic:dic];
        [arr addObject:model];
    }
    _modelArr = arr;
    [_showCollectionView reloadData];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(ScaleX * 375,ScaleY * 603);
    layout.scrollDirection = 1;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    _showCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, ScaleX * 375, ScaleY * 603) collectionViewLayout:layout];
    _showCollectionView.delegate = self;
    _showCollectionView.dataSource = self;
    _showCollectionView.pagingEnabled = YES;
    [_showCollectionView registerClass:[ZGLPhotoCell class] forCellWithReuseIdentifier:@"ceklkk"];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:_showCollectionView];
}
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = backColor;
    _titleView.backgroundColor = naviColor;
    _showCollectionView.backgroundColor = backColor;
    self.tabBarController.tabBar.hidden = YES;
    [_showCollectionView reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = backColor;
    [self createCollectionView];
    [self setNavigationBar];
    // Do any additional setup after loading the view.
}


#pragma mark - collectionViewdelegate & datasource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _modelArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGLPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ceklkk" forIndexPath:indexPath];
    
    if (_modelArr.count > 0) {
        cell.model = _modelArr[indexPath.item];
        cell.currentCount = indexPath.item + 1;
        _currentPage = indexPath.item;
        cell.allCount = _modelArr.count;
    }
    
    return cell;
}


- (CGSize)blockSizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    
    return CGSizeMake(1, 1);
    
    
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
